package logic

import (
	"context"
	"fmt"
	"house/cache"
	"house/houserpc/houserpc"
	"house/houserpc/internal/svc"
	"house/models"
	"house/pkg"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 用户登录
func (l *UserLoginLogic) UserLogin(in *houserpc.UserLoginRequest) (*houserpc.UserLoginResponse, error) {
	// todo: add your logic here and delete this line

	var user models.User
	models.DB.Debug().Where("account = ?", in.Account).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("当前账号未注册,登录失败")
	}

	if user.Password != pkg.Md5(in.Password) {
		return nil, fmt.Errorf("账号密码错误,登录失败")
	}

	result, _ := cache.Rdb.Get(l.ctx, "captcha"+in.Account).Result()
	if result != in.Captcha {
		return nil, fmt.Errorf("图形验证码错误,登录失败")
	}

	result1, _ := cache.Rdb.Get(l.ctx, "sendSms = ?"+in.Account).Result()
	if result1 != in.SendSms {
		return nil, fmt.Errorf("短信验证码错误,登录失败")
	}

	return &houserpc.UserLoginResponse{
		UserId: int64(user.ID),
	}, nil
}
